<script setup lang="ts">
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { Card } from 'ant-design-vue';
  import { PageWrapper } from '@/components/Page';
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from '@/views/resource/script/util/script.data';
  import { scriptAddOrUpdate } from '@/api/resource/scriptManage';
  import CodeModule from '@/views/resource/script/CodeModule.vue';

  const emit = defineEmits(['success', 'register']);
  const codeRef = ref();
  const isUpdate = ref(true);
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 12 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      if (undefined !== data.record.scriptContent) {
        codeRef.value.putCode(data.record.scriptContent);
      }
    }
    setFieldsValue({
      ...data.record,
    });
  });
  const getTitle = computed(() => (!unref(isUpdate) ? '新增脚本' : '编辑脚本'));

  async function handleSubmit() {
    try {
      const values = await validate();
      values.scriptContent = codeRef.value.code;
      setDrawerProps({ confirmLoading: true });
      await scriptAddOrUpdate(values);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>

<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="70%"
    @ok="handleSubmit"
  >
    <PageWrapper>
      <Card title="基本信息" :bordered="false">
        <BasicForm @register="registerForm" />
      </Card>
      <Card title="脚本内容" :bordered="false">
        <CodeModule ref="codeRef" />
      </Card>
    </PageWrapper>
  </BasicDrawer>
</template>
